Ext.ns('Portal.contactScreen');

Ext.apply(Portal.contactScreen, {
    //functie de export ..
    fnExportBaza: function() {

        var BazaForm = Ext.getCmp(Portal.contactScreen.id).find("itemId", "search")[0];
        BazaForm.getForm().getEl().dom.action = "Contact/Export/" ;
        BazaForm.getForm().getEl().dom.target = '_blank';
        BazaForm.getForm().getEl().dom.submit();
    },
      /*
    //functie de stergere / editare inregistrare
    action: function () {
        var oGrid, iRec = 0, oWind, op = "edit";

        oGrid = Ext.getCmp(Portal.contactScreen.id).find("itemId", "ContactGrid")[0];

        //setare tip operatie; daca este butonul de adaugare / editare atunci se citeste paramentrul `action` al acestuia
        if (this.action) {
            op = this.action;
        }

        if (op === "edit") {
            if (oGrid.selModel.getCount() != 1) {
                Portal.events.throwInformation("Selectati o inregistrare !");
                return;
            }
            iRec = oGrid.selModel.getSelected().id;
        }

        //constructie formular
        var oFpAdd = new Ext.FormPanel({
            autoHeight: true, //inaltimea formului va da inaltimea ferestrei
            labelWidth: 160,
            frame: true,
            bodyStyle: {
                padding: "5px"
            },
            layout: 'form',
            defaults: {
                anchor: '90%',
                xtype: "textfield",
                allowBlank: false
            },
            items: [
                {
                    name: 'LastName',
                    fieldLabel: 'Nume'
                },
                {
                    name: 'FirstName',
                    fieldLabel: 'Prenume'
                },
                {
                    name: 'Sex',
                    fieldLabel: 'Sex'
                },
                {
                    name: 'Position',
                    fieldLabel: 'Functie'
                },
                {
                    name: 'Subposition',
                    fieldLabel: 'Subfunctie'
                },
                {
                    name: 'Company',
                    fieldLabel: 'Companie'
                },
                {
                    name: 'Address',
                    fieldLabel: 'Adresa'
                },
                {
                    name: 'City',
                    fieldLabel: 'Oras'
                },
                {
                    name: "IdContact",
                    xtype: "hidden",
                    value: iRec
                }
            ],
            buttons: [
                {
                    text: 'Salvare',
                    handler: function () {

                        if (!oFpAdd.getForm().isValid()) {
                            return;
                        }

                        oFpAdd.getForm().submit({
                            url: "Contact/EditContact",
                            success: function (form, response) {
                                oGrid.store.reload();
                                oWind.close();
                            }
                        });
                    }
                }
            ]
        });

        //constructie fereastra
        oWind = new Ext.Window({
            title: (op === "edit") ? "Editare inregistrare" : "Adaugare inregistrare",
            width: 450,
            layout: 'fit',
            modal: true,
            closeAction: 'close',
            items: [oFpAdd]
        }).show();

        //daca este editare de inregistrare atunci se aduc datele acestei inregistrari
        if (op === "edit") {
            oFpAdd.on("afterlayout", function () {
                        Ext.Ajax.request({
                            url: 'Contact/GetContactById',
                            params: {
                                Id: iRec
                            },
                            success: function (response) {
                                var oRes = Ext.decode(response.responseText);
                                var oData = oRes.Records;
                                fnCompleteForm(oFpAdd, oData[0]);  //vezi utils.js
                            }
                        })
                    }, this, { single: true });
        }
    }   ,
          */

    fnMoveContactCampaignContact: function(operation, confirmationText) {

        var gpContact = Ext.getCmp(Portal.contactScreen.id).find("itemId", "ContactGrid")[0];
        var gridCampaign = Ext.getCmp(Portal.contactScreen.id).find("itemId", "CampaignGrid")[0];

        Ext.MessageBox.confirm('Confirm', confirmationText,
                function(btn) {
                    if (btn == 'yes') {
                        //conditie de stergere : sa fie selectata cel putin 1 persoana si o campanie
                        if ((gpContact.selModel.getCount() >= 1) && (gridCampaign.selModel.getCount() == 1)) {

                            var selection = gpContact.selModel.getSelections();
                            var prez = [];

                            for (i = 0; i < gpContact.selModel.getCount(); i++) {
                                prez.push(selection[i].id);
                            }
                            //selectie din gridul de campanii
                            var campaignSelected = gridCampaign.selModel.getSelected();

                            Ext.Ajax.request({
                                url: "Campaign/MoveDeleteContact/" ,
                                params: {
                                    op: operation,
                                    contacts: Ext.encode(prez),
                                    id_campaign: campaignSelected.id
                                },
                                success: function(response) {
                                    if (response.responseText) {
                                        var oRes = Ext.util.JSON.decode(response.responseText);
                                        if (oRes.description) {
                                            Ext.example.msg('Atentie', oRes.description);
                                        }
                                    }
                                    gridCampaign.getStore().reload();
                                }
                            });
                        }
                        else {
                            Ext.example.msg("Atentie", "Selectati cel putin un contact si o campanie!");
                        }
                    }
                });
    }
});

Ext.apply(Portal.contactScreen, {

    id: 'idTabcontactScreen',
    exec: function () {

        if (!Ext.getCmp(Portal.contactScreen.id)) {


            var filterName = new Ext.form.TextField({
                itemId : "LastName",
                name: 'LastName',
                fieldLabel: 'Nume'
            });

            var filterFName = new Ext.form.TextField({
                itemId : "FirstName",
                name: 'FirstName',
                hiddenName: 'FirstName',
                fieldLabel: 'Prenume'
            });

            var filterEmail = new Ext.form.TextField({
                itemId : "Email",
                name: 'Email',
                hiddenName: 'Email',
                fieldLabel: 'Email'
            });

            var filterCompany = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Company',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "addCompany",
                itemId: "company",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    readerFields: [
                        { name : "Id",  mapping : "idCompany"  },
                        { name : "Name", mapping : "companyName" }
                    ]  ,
                    baseParams: {},
                    proxyUrl: 'Company/GetCompany/'
                }
            });

            var filterAddress = new Ext.form.TextField({
                itemId : "Address",
                name: 'Address',
                fieldLabel: 'Adresa'
            });
            var filterCounty = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Judet',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "addCounty",
                itemId: "county",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'County/GetCounty/'
                },
                listeners: {
                    select:  function (combo, value) {
                        cbCity = fpSearch.find("itemId", "city")[0];
                        cbCity.setValue('');
                        cbCity.store.load({
                            params : {
                                county_id : combo.getValue()
                            }
                        });
                    }
                }

            });
            var filterCity = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'City',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "addCity",
                itemId: "city",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'City/GetCity/'
                }

            });


            var filterDomain = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Domeniu',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "addDomain",
                itemId: "domain",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table: "domains"
                    },
                    proxyUrl: 'Domain/GetDomain/'
                },
                listeners: {
                    select:  function (combo, value) {
                        cbSubDomain = fpSearch.find("itemId", "subdomain")[0];
                        cbSubDomain.setValue('');
                        cbSubDomain.setDisabled(false);
                        cbSubDomain.store.load({ params : {
                            domain_id : combo.getValue()
                        }
                        });
                    }
                }
            });
            var filterSubDomain = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Subdomeniu',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "addSubdomain",
                itemId: "subdomain",
                disabled : true,
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'Subdomain/GetSubdomain/'
                }
            });

            var filterPosition = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Functie',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_position",
                itemId: "position",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'Position/GetPosition/'
                },
                listeners: {
                    select:  function (combo, value) {
                        cbSubPos = fpSearch.find("itemId", "subposition")[0];
                        cbSubPos.setValue('');
                        cbSubPos.setDisabled(false);
                        cbSubPos.store.load({ params : {
                            position_id : combo.getValue()
                        }
                        });
                    }
                }
            });

            var filterSubPosition = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Subfunctie',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_subposition",
                itemId: "subposition",
                disabled : true,
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'Subposition/GetSubposition/'
                }
            });

            var filterClient = new Ext.ux.form.LovCombo({
                itemId : "Campain",
                fieldLabel: 'Campanie',
                store: new Ext.data.SimpleStore({
                    fields: ['optionValue', 'optionDisplay', 'optionDisplayCount'],
                    data:[]
                }),
                name: 'client_id',
                hiddenName: 'client_id',
                mode: 'local',
                width: 80,
                displayField: 'optionDisplay',
                valueField: 'optionValue'
            });

            var filterSex = new Ext.ux.fastCombo.Combo({

                fieldLabel : "Sex",
                xtype : "uxFCombo",
                editable : false,
                name : "Sex",
                easyConfig: {
                    mode : "local",
                    localData: [
                        ['1', 'F'],
                        ['2', 'M']
                    ]
                }

            });
            var filterPriority = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Prioritate',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_priority",
                itemId: "priority",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table_name:'priority'
                    },
                    proxyUrl: 'Nom/GetNom/'
                }
            });

            var filterAvailable = new Ext.ux.fastCombo.Combo({

                fieldLabel : "Disponibil",
                xtype : "uxFCombo",
                editable : false,
                name : "available",
                easyConfig: {
                    mode : "local",
                    localData: [
                        ['1', 'Da'],
                        ['2', 'Nu']
                    ]
                }

            });

            var filteUnsubscribed = new Ext.ux.form.LovCombo({
                itemId : "Dezabonati",
                fieldLabel: 'Dezabonati',
                store: new Ext.data.SimpleStore({
                    fields: ['optionValue', 'optionDisplay', 'optionDisplayCount'],
                    data:[]
                }),
                name: 'unsubscribed',
                hiddenName: 'unsubscribed',
                mode: 'local',
                width: 80,
                displayField: 'optionDisplayCount',
                valueField: 'optionValue'
            });

            var filterIncome = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Venit',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_income",
                itemId: "income",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table_name:'income'
                    },
                    proxyUrl: 'Nom/GetNom/'
                }
            });

            var filterAge = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Varsta',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_age",
                itemId: "age",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table_name:'age'
                    },
                    proxyUrl: 'Nom/GetNom/'
                }
            });
            var filterUser = new Ext.ux.form.LovCombo({
                itemId : "User",
                name: 'user',
                hiddenName: 'user',
                fieldLabel: 'User',
                store: new Ext.data.SimpleStore({
                    fields: ['optionValue', 'optionDisplay'],
                    data:[]
                }),
                mode: 'local',
                width: 80,
                displayField: 'optionDisplay',
                valueField: 'optionValue'
            });
            var filterDivision = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Departament',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "id_division",
                itemId: "dept",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {},
                    proxyUrl: 'Division/GetDivision/'
                }
            });

            var filterLetter = new Ext.ux.form.LovCombo({
                itemId : "Litere",
                fieldLabel: 'Litere',
                store: new Ext.data.SimpleStore({
                    fields: ['optionValue', 'optionDisplay', 'optionDisplayCount'],
                    data:[]
                }),
                name: 'letter',
                hiddenName: 'letter',
                mode: 'local',
                width: 80,
                displayField: 'optionDisplay',
                valueField: 'optionValue'
            });
            var filterEmployee = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Angajati',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "employee",
                itemId: "employee",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table_name:'employee'
                    },
                    proxyUrl: 'Nom/GetNom/'
                }
            });


            var filterTurnover = new Ext.ux.fastCombo.Combo({
                fieldLabel: 'Cifra afaceri',
                xtype: "uxFCombo",
                anchor: "70%",
                name: "turnover",
                itemId: "turnover",
                forceSelection: false,
                minChars: 2,
                easyConfig: {
                    baseParams: {
                        table_name:'turnover'
                    },
                    proxyUrl: 'Nom/GetNom/'
                }
            });

            var filterCreatedFrom = new Ext.form.DateField({
                itemId : "Creat",
                fieldLabel: 'Creat de la',
                name: 'createdfrom',
                format: 'Y-m-d',
                width: 120
            });
            var filterModFrom = new Ext.form.DateField({
                itemId : "Modificat",
                fieldLabel: 'Modif. de la',
                format: 'Y-m-d',
                name: 'modfrom',
                width: 120
            });
            var filterEnd = new Ext.form.DateField({
                itemId : "Pana la",
                fieldLabel: 'Pana de la',
                name: 'end',
                format: 'Y-m-d',
                width: 120
            });
            var filterCustom = new Ext.form.ComboBox({
                itemId : "Diverse",
                fieldLabel: 'Diverse',
                store: new Ext.data.SimpleStore({
                    fields: ['optionValue', 'optionDisplay'],
                    data: [
                        ["dubluri", "Dubluri"]
                    ]
                }),
                listWidth: 200,
                name: 'custom',
                hiddenName: 'custom',
                mode: 'local',
                width: 80,
                displayField: 'optionDisplay',
                valueField: 'optionValue'
            });


            //PANEL DE FILTRE
            var fpSearch = new Ext.FormPanel({
                region: 'north',
                bodyStyle: 'padding: 0',
                border: false,
                autoScroll: false,
                buttonAlign: 'center',
                itemId:"search",
                labelWidth: 74,
                height: 220,
                frame: true,
                items: [
                    {
                        xtype: "tabpanel",
                        defaults: { autoHeight: true, frame: true },
                        activeTab: 1,
                        items: [
                            {
                                layout: 'column',
                                title: "Filtre Companie",
                                defaults: {
                                    layout: 'form',
                                    columnWidth: 0.25,
                                    defaults: {
                                        triggerAction: 'all',
                                        itemCls: 'x-form-item-filter',
                                        listWidth: 250,
                                        anchor: "95%"
                                    }
                                },
                                items: [
                                    {
                                        items: [filterCompany, filterLetter, filterDomain, filterSubDomain]
                                    },
                                    {
                                        items: [filterAddress,  filterCounty, filterCity]
                                    },
                                    {
                                        items: [filterEmployee, filterClient, filterTurnover]
                                    }
                                ]
                            },
                            {
                                layout: 'column',
                                title: "Filtre Contact",
                                defaults: {
                                    layout: 'form',
                                    columnWidth: 0.25,
                                    defaults: {
                                        triggerAction: 'all',
                                        listWidth: 300,
                                        anchor: "95%",
                                        itemCls: 'x-form-item-filter'
                                    }
                                },
                                items: [
                                    {
                                        items: [filterName, filterFName, filterSex, filterAge]
                                    },
                                    {
                                        items: [filterPosition, filterSubPosition, filterDivision]
                                    },
                                    {
                                        items: [filterPriority, filterAvailable, filterIncome]
                                    }
                                ]
                            },
                            {
                                layout: 'column',
                                title: "Altele",
                                defaults: {
                                    layout: 'form',
                                    columnWidth: 0.25,
                                    defaults: {
                                        triggerAction: 'all',
                                        listWidth: 300,
                                        anchor: "95%",
                                        itemCls: 'x-form-item-filter'
                                    }
                                },
                                items: [
                                    {
                                        items: [filterUser, filterEmail, filteUnsubscribed]
                                    },
                                    {
                                        items: [filterCreatedFrom, filterModFrom, filterEnd]
                                    },
                                    {
                                        items: [filterCustom]
                                    }
                                ]
                            }
                        ]
                    }
                ],
                buttons: [
                    {
                        text: 'Cauta',
                        iconCls: 'icon-zoom',
                        handler: function () {
                            oContactGrid.store.reload({
                                params :   fpSearch.getForm().getValues()
                            })
                        }
                    },
                    {
                        text: 'Reset',
                        iconCls: 'icon-link-break',
                        handler: function () {
                            fpSearch.getForm().reset();
                            oContactGrid.store.reload({
                                params :   fpSearch.getForm().getValues()
                            })
                        }
                    },
                    {
                        text: 'Exporta',
                        iconCls: 'icon-page-excel'   ,
                        handler: Portal.contactScreen.fnExportBaza
                    }
                ]
            });


            var smContact = new Ext.grid.CheckboxSelectionModel({
                singleSelect: false
            });

            var oCmContact = new Ext.grid.ColumnModel({
                columns: [
                    smContact,
                    {
                        header: "Nume",
                        dataIndex: 'LastName',
                        width: 100
                    },
                    {
                        header: "Prenume",
                        dataIndex: 'FirstName',
                        width: 100
                    },
                    {
                        header: "Sex",
                        dataIndex: 'Sex'
                    },
                    {
                        header: "Functie",
                        dataIndex: 'PositionName'
                    },
                    {
                        header: "Subfunctie",
                        dataIndex: 'SubPositionName'
                    },
                    {
                        header: "Companie",
                        dataIndex: 'CompanyName'
                    },
                    {
                        header: "Adresa",
                        dataIndex: 'Address'
                    },
                    {
                        header: "Oras",
                        dataIndex: 'CityName'
                    }
                ],
                defaults: {
                    sortable: true
                }
            });


            var oContactGrid = new Ext.ux.fastGrid({
                xtype: "uxFGrid",
                layout: 'fit',
                itemId: "ContactGrid",
                region: 'center',
                sm:smContact,
                gridConfig: {
                    url: 'Contact/GetContacts',
                    fields: ['IdContact', 'LastName', 'FirstName', 'Sex', 'PositionName', 'SubPositionName','CompanyName','Address','CityName',                                        'Available'],
                    viewConfig: {
                        getRowClass: function (record, index) {
                            var cls = "", c;
                            c = record.get('available');
                            if (c == 0) {
                                cls = cls + ' inactive-row';
                            }
                            return cls;
                        }
                    }
                },
                cm: oCmContact,
                tbar: [
                    {
                        text: "Adauga",
                        iconCls: 'icon-add',
                        action: "add",
                        handler: function() {
                            var contact = {
                                id: "new_" + parseInt(new Date().getTime()),
                                name: "Contact",
                                sex: 0
                            }
                            Portal.contactForm.exec(contact);
                        }
                    },
                    '-',
                    {
                        text: 'Muta',
                        tooltip: 'Muta persoanele selectate pe campanie',
                        iconCls: 'icon-cog-add',
                        handler: function() {
                            Portal.contactScreen.fnMoveContactCampaignContact(1, "Sunteti sigur(a) ca vreti sa mutati ?");
                        }
                    },
                    {
                        text: 'Sterge',
                        tooltip: 'Sterge persoanele selectate pe campanie',
                        iconCls: 'icon-cog-delete',
                        handler: function() {
                            Portal.contactScreen.fnMoveContactCampaignContact(0, "Sunteti sigur(a) ca vreti sa stergeti de pe campanie ?");
                        }
                    }
                ],
                listeners: {
                    'rowdblclick': function(grid, rowIndex, e) {
                        if (grid.selModel.getCount() == 1) {
                            var selection = grid.selModel.getSelected();
                            var contact = {
                                id: selection.data.IdContact,
                                name: selection.data.LastName + " " + selection.data.FirstName,
                                sex: selection.data.Sex
                            }
                            Portal.contactForm.exec(contact);
                        }
                    }
                }
            });

            var oCmCampaign = new Ext.grid.ColumnModel({
                columns: [
                    {
                        header: "Campanie",
                        dataIndex: 'Name'
                    }   ,
                    {
                        header: "Nr. Contacte",
                        dataIndex: 'NrContact'
                    }
                ],
                defaults: {
                    sortable: true
                }
            });

            var oCampaignGrid = new Ext.ux.fastGrid({
                xtype: "uxFGrid",
                layout: 'fit',
                title:"Campanii",
                itemId: "CampaignGrid",
                region: 'center',
                gridConfig: {
                    url: 'Campaign/GetCampaignCount',
                    fields: ['Id', 'Name', 'NrContact']
                },
                cm: oCmCampaign
            });


            var oWest = new Ext.TabPanel({
                region: 'west',
                //layout: 'border',
                deferredRender: false,
                tabPosition: 'bottom',
                width: 160,
                collapsible: true,
                activeTab: 0,
                items: [oCampaignGrid]
            });


            var oCenter = {
                region: 'center',
                layout: 'border',
                items: [oContactGrid, fpSearch]
            };

            //creare tab ce contine gridul
            var oNomTab = new Ext.Panel({
                title: 'Contacte',
                id: Portal.contactScreen.id,
                iconCls: 'icon-group',
                closable: true,
                layout: 'border',
                items: [oCenter,oWest]
            });


            //adaugare tab la tabpanel-ul principal
            Portal.oCenterRegion.add(oNomTab);
            Portal.oCenterRegion.doLayout();

        }
        //activare tab
        Portal.oCenterRegion.setActiveTab(Portal.contactScreen.id);
    }
});